/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package visao.pedido;

import controle.modelo.ControleCliente;
import controle.modelo.ControlePedido;
import controle.modelo.ControleTipoDePagamento;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import modelo.Cliente;
import modelo.Linha;
import modelo.Pedido;
import modelo.Produto;
import modelo.TipoDePagamento;
import modelo.Usuario;

/**
 *
 * @author Luiz Cunha
 */
public class CriarPedidoForm extends javax.swing.JFrame
{

    Cliente cliente;
    ControleCliente controleCliente;
    ControleTipoDePagamento controleTipoDePagamento;

    List<TipoDePagamento> tiposDePagamento;
    Pedido thisPedido;
    ControlePedido controlePedido = new ControlePedido();
    Integer thisIdPedido;
    Usuario loggedUsuario;

    /**
     * Creates new form CriarPedidoForm
     */
    public CriarPedidoForm(Usuario loggedUsuario)
    {
        initComponents();
        logicaDaCheckbox();
        controleCliente = new ControleCliente();
        controleTipoDePagamento = new ControleTipoDePagamento();
        tiposDePagamento = controleTipoDePagamento.getAllTiposDePagamento();
        String[] tiposDePagamentoCombo = new String[tiposDePagamento.size()];
        for (int i = 0; i < tiposDePagamento.size(); i++)
        {
            tiposDePagamentoCombo[i] = tiposDePagamento.get(i).getDescricao();
        }
        DefaultComboBoxModel model = new DefaultComboBoxModel(tiposDePagamentoCombo);
        jComboBoxTipoDePagamento.setModel(model);

        thisPedido = new Pedido();
        thisPedido.setCalendar(Calendar.getInstance());

        this.loggedUsuario = loggedUsuario;
        
        thisPedido = new Pedido();
        
        thisPedido.setCalendar(Calendar.getInstance());

        thisPedido.setUsuario(loggedUsuario);

        thisPedido.setTipoDePagamento(controleTipoDePagamento.getTipoDePagamentoByDescricao((String) jComboBoxTipoDePagamento.getSelectedItem()));

        thisPedido.setLinhas(new ArrayList<Linha>());
        
        thisIdPedido = controlePedido.addPedido(thisPedido);
    }

    private void logicaDaCheckbox()
    {
        if (jCheckBox1.isSelected())
        {
            jTextFieldCliente.setEditable(false);
            jButtonPesquisaCliente.setEnabled(false);
        }
        else
        {
            jTextFieldCliente.setEditable(true);
            jButtonPesquisaCliente.setEnabled(true);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents()
    {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jTextFieldCliente = new javax.swing.JTextField();
        jButtonPesquisaCliente = new javax.swing.JButton();
        jComboBoxTipoDePagamento = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTablePedido = new javax.swing.JTable();
        jLabel6 = new javax.swing.JLabel();
        jCheckBox1 = new javax.swing.JCheckBox();
        jButtonAddProduto = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel1.setText("Novo Pedido");

        jLabel2.setText("Cliente:");

        jLabel5.setText("Tipo de pagamento:");

        jTextFieldCliente.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jTextFieldClienteActionPerformed(evt);
            }
        });

        jButtonPesquisaCliente.setText("Pesquisar");
        jButtonPesquisaCliente.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jButtonPesquisaClienteActionPerformed(evt);
            }
        });

        jComboBoxTipoDePagamento.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        jComboBoxTipoDePagamento.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jComboBoxTipoDePagamentoActionPerformed(evt);
            }
        });

        jTablePedido.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][]
            {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String []
            {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTablePedido);

        jLabel6.setText("Produtos:");

        jCheckBox1.setSelected(true);
        jCheckBox1.setText("Pedido varejo");
        jCheckBox1.addChangeListener(new javax.swing.event.ChangeListener()
        {
            public void stateChanged(javax.swing.event.ChangeEvent evt)
            {
                jCheckBox1StateChanged(evt);
            }
        });
        jCheckBox1.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jCheckBox1ActionPerformed(evt);
            }
        });

        jButtonAddProduto.setText("Adicionar produto");
        jButtonAddProduto.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jButtonAddProdutoActionPerformed(evt);
            }
        });

        jButton2.setText("Confirmar dados do cliente");
        jButton2.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Atualizar Pedido");
        jButton3.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setText("Salvar");
        jButton4.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jButton4ActionPerformed(evt);
            }
        });

        jButton5.setText("Cancelar");
        jButton5.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jButton5ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(289, 289, 289)
                .addComponent(jLabel1)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addGap(73, 73, 73)
                                .addComponent(jTextFieldCliente))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jComboBoxTipoDePagamento, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(51, 51, 51)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jButtonPesquisaCliente)
                                .addGap(18, 18, 18)
                                .addComponent(jCheckBox1))
                            .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 188, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 751, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonAddProduto))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jButton4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton5)
                        .addGap(2, 2, 2)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jButtonPesquisaCliente)
                            .addComponent(jCheckBox1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(jTextFieldCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel5)
                            .addComponent(jComboBoxTipoDePagamento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGap(60, 60, 60)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(jButtonAddProduto)
                    .addComponent(jButton3))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 331, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton4)
                    .addComponent(jButton5))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jTextFieldClienteActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jTextFieldClienteActionPerformed
    {//GEN-HEADEREND:event_jTextFieldClienteActionPerformed

    }//GEN-LAST:event_jTextFieldClienteActionPerformed

    private void jButtonPesquisaClienteActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButtonPesquisaClienteActionPerformed
    {//GEN-HEADEREND:event_jButtonPesquisaClienteActionPerformed
        List<Cliente> clientes = controleCliente.getClienteNomeLike(jTextFieldCliente.getText());
        if (clientes.size() > 1)
        {
            JFrame newFrame = new JFrame("Escolher cliente");
            newFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

            String[] columnNames =
            {
                "Id", "Nome", "Endereço", "Email"
            };
            String[][] rowData = new String[clientes.size()][4];
            for (int i = 0; i < clientes.size(); i++)
            {
                rowData[i][0] = clientes.get(i).getIdCliente().toString();
                rowData[i][1] = clientes.get(i).getNome();
                rowData[i][2] = clientes.get(i).getEndereco();
                rowData[i][3] = clientes.get(i).getEmail();
            }
            final javax.swing.JTable tableDeClientes = new JTable(rowData, columnNames);
            javax.swing.JButton okBttn = new JButton("Escolher");
            okBttn.addActionListener(new ActionListener()
            {

                @Override
                public void actionPerformed(ActionEvent e)
                {
                    int selectedRowIndex = tableDeClientes.getSelectedRow();
                    int desiredColumn = 0;
                    String selectedId = (String) tableDeClientes.getModel().getValueAt(selectedRowIndex, desiredColumn);
                    cliente = controleCliente.getClienteById(Integer.valueOf(selectedId));
                    jTextFieldCliente.setText(cliente.getNome());

                }
            });

            tableDeClientes.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
            newFrame.setLayout(new FlowLayout());
            newFrame.getContentPane().add(tableDeClientes);
            newFrame.getContentPane().add(okBttn);

            newFrame.pack();
            newFrame.setVisible(true);

        }
        else if (clientes.size() < 1)
        {
            JOptionPane.showMessageDialog(null, "Não foi encontrado nenhum cliente de acordo com o criterio escrito");
        }
        else
        {
            cliente = clientes.get(0);
        }

        jTextFieldCliente.setText(cliente.getNome());
    }//GEN-LAST:event_jButtonPesquisaClienteActionPerformed

    private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jCheckBox1ActionPerformed
    {//GEN-HEADEREND:event_jCheckBox1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jCheckBox1ActionPerformed

    private void jCheckBox1StateChanged(javax.swing.event.ChangeEvent evt)//GEN-FIRST:event_jCheckBox1StateChanged
    {//GEN-HEADEREND:event_jCheckBox1StateChanged
        if (jCheckBox1.isSelected())
        {
            jTextFieldCliente.setEditable(false);
            jButtonPesquisaCliente.setEnabled(false);
        }
        else
        {
            jTextFieldCliente.setEditable(true);
            jButtonPesquisaCliente.setEnabled(true);
        }


    }//GEN-LAST:event_jCheckBox1StateChanged

    private void jComboBoxTipoDePagamentoActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jComboBoxTipoDePagamentoActionPerformed
    {//GEN-HEADEREND:event_jComboBoxTipoDePagamentoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jComboBoxTipoDePagamentoActionPerformed


    private void jButtonAddProdutoActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButtonAddProdutoActionPerformed
    {//GEN-HEADEREND:event_jButtonAddProdutoActionPerformed

        if (cliente != null)
        {
            thisPedido.setCliente(cliente);
        }

        

        AdicionarLinhaForm form = new AdicionarLinhaForm(thisIdPedido);
        form.setVisible(true); 
        


    }//GEN-LAST:event_jButtonAddProdutoActionPerformed

    public void updateTabela()
    {
        
        thisPedido = controlePedido.getPedidoById(thisIdPedido);

        String[] colunas =
        {
            "Descricao", "Quantidade", "Valor"
        };
        String[][] data = new String[thisPedido.getLinhas().size()][3];

        for (int i = 0; i < thisPedido.getLinhas().size(); i++)
        {
            data[i][0] = thisPedido.getLinhas().get(i).getProduto().getDescricao();
            data[i][1] = thisPedido.getLinhas().get(i).getQuantidade().toString();
            if (thisPedido.getCliente() == null)
            {
                data[i][2] = thisPedido.getLinhas().get(i).getProduto().getPrecoVarejo().toString();
            }
            else
            {
                data[i][2] = thisPedido.getLinhas().get(i).getProduto().getPrecoRevenda().toString();
            }
        }
        jTablePedido.setModel(new DefaultTableModel(data, colunas));
    }

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton2ActionPerformed
    {//GEN-HEADEREND:event_jButton2ActionPerformed
        if (cliente != null)
        {
            JOptionPane.showMessageDialog(null, cliente.toString());
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton3ActionPerformed
    {//GEN-HEADEREND:event_jButton3ActionPerformed
        updateTabela();
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton4ActionPerformed
    {//GEN-HEADEREND:event_jButton4ActionPerformed
       dispose();
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton5ActionPerformed
    {//GEN-HEADEREND:event_jButton5ActionPerformed
       controlePedido.deletePedido(thisPedido);
    }//GEN-LAST:event_jButton5ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[])
    {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try
        {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels())
            {
                if ("Nimbus".equals(info.getName()))
                {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        }
        catch (ClassNotFoundException ex)
        {
            java.util.logging.Logger.getLogger(CriarPedidoForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (InstantiationException ex)
        {
            java.util.logging.Logger.getLogger(CriarPedidoForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (IllegalAccessException ex)
        {
            java.util.logging.Logger.getLogger(CriarPedidoForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (javax.swing.UnsupportedLookAndFeelException ex)
        {
            java.util.logging.Logger.getLogger(CriarPedidoForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
//                new CriarPedidoForm().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButtonAddProduto;
    private javax.swing.JButton jButtonPesquisaCliente;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JComboBox jComboBoxTipoDePagamento;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTablePedido;
    private javax.swing.JTextField jTextFieldCliente;
    // End of variables declaration//GEN-END:variables
}
